package com.atguigu.educenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionHandler.MyHandler;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.logging.Handler;

@Controller     //RestController 会返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    //获取扫码人的信息，添加到数据库
    @GetMapping("callback")
    public String callBack(String code,String state){
        //使用code请求微信的固定地址
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        String accessUrl = String.format(baseAccessTokenUrl,ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,code);
        String jwtToken ="";
        //请求地址  得到access_token and openid
        try {
            String info = HttpClientUtils.get(accessUrl);
            //将info转换成map格式
            Gson gson = new Gson();
            HashMap mapToken = gson.fromJson(info, HashMap.class);
            String access_token = (String) mapToken.get("access_token");
            String openid = (String) mapToken.get("openid");
            //把扫码人信息添加到数据库
            //判断数据库中是否有openId 若存在就不添加
            UcenterMember member = ucenterMemberService.getOpenIdMember(openid);
            if(member==null){
                //再去访问微信地址
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //将userInfo转换为map
                HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String)mapUserInfo.get("nickname");
                String headimgurl = (String)mapUserInfo.get("headimgurl");

                //向表中添加
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
                //使用jwt根据member对象生成token
                jwtToken = JwtUtils.getJwtToken(member.getId(),member.getNickname());
            }

        } catch (Exception e) {
            throw new MyHandler(20001,"登录失败");
        }
        return "redirect:http://localhost:3000?token="+jwtToken;
    }

    //生成微信扫描的二维码
    @GetMapping("loginWx")
    public String getWxCode(){
        //通过return重定向到一个网址
        //请求微信地址
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");

        return "redirect:" + url;
    }
}
